package com.my.socket.nio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
import java.util.Set;

/**
 * User: Alex Zhong
 * Date: 2016/6/17
 */
public class Client {
    private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));

        socketChannel.register(selector, SelectionKey.OP_CONNECT);

        while (true) {
            selector.select();

            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            for (SelectionKey selectionKey : selectionKeys) {
                selectionKeys.remove(selectionKey);

                if (selectionKey.isConnectable()) {
                    SocketChannel client = (SocketChannel) selectionKey.channel();

                    if (client.isConnectionPending()) {
                        client.finishConnect();
                    }
                    client.configureBlocking(false);

                    LOGGER.info("please input some thing:");
                    Scanner scanner = new Scanner(System.in);
                    String message = scanner.nextLine();
                    client.write(ByteBuffer.wrap(message.getBytes()));
                    LOGGER.info("send the message [{}] to the server", message);

                    client.register(selector, SelectionKey.OP_READ);
                } else if (selectionKey.isReadable()) {
                    SocketChannel selectableChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(15);
                    selectableChannel.read(byteBuffer);
                    String message = new String(byteBuffer.array());
                    LOGGER.info("receive the message [{}] from the server", message);
                }
            }
        }
    }
}
